
var $refresh = $('#refresh');
var $pageBox = $('.pagination');
var handleid = userid;
var appealList = $('#table');
var imagepaths = [];

// 按条件查找下拉框初始化
$(document).ready(function() {
    $('#categoryList').multiselect({
        buttonText: function(options, select) {
            if (options.length === 0) {
                return '-- 企业类型--';
            }
            else if (options.length > 0) {
                return '已选查询条件';
            }
        }
    });
    $('#appealtypeList').multiselect({
        buttonText: function(options, select) {
            if (options.length === 0) {
                return '-- 事项划分--';
            }
            else if (options.length > 0) {
                return '已选查询条件';
            }
        }
    });
});

// 获取所有待处理诉求
var paging = function (pageNum,tj) {
    $.ajax({
        url: appBaseURL + '/appeal/todoTaskByHandleid/',
        type: 'POST',
        data: JSON.stringify(tj) || JSON.stringify({"userid":userid,"taskstatusList":[3],"pageNum":pageNum || 1,"pageSize":20}),
        contentType: "application/json",
        success: function (info) {
            if(info.code == 0){
                // 调用模板引擎
                appealList.html(template('disposeTpl', {list: info.data.list}));
                // 分页按钮
                $pageBox.html(template('page', {
                    model: {
                        'pageNum':info.data.pageNum,
                        'pageCount': info.data.pages
                    }
                }));
                var tempStr = "共"+info.data.total+"条 第"+(pageNum || 1)+"/"+info.data.pages+"页";  
                document.getElementById("barcon1").innerHTML = tempStr; 
                var tempOption="";
                var currentPage = pageNum || 1;//当前页数 
                    currentPage_ = currentPage;
                for(var i = 1; i <= info.data.pages; i++) {  
                    tempOption+='<option value='+i+'>'+i+'</option>'  
                }  
                $("#jumpWhere").html(tempOption);
                $("#jumpWhere").val(currentPage || 1);
                window.pageNow = info.data.pageNum;
            }else{
                toastr.error("请求失败，请稍后再试！");
            }
        },
        error: function () {
            toastr.error("请求失败，请稍后再试！");
        } 
    });
}
// 页面初始化
paging();
// 换页
$pageBox.on('click', 'a', function () {
    if($(this).hasClass('disabled')||$('.overlay:visible').length) return false;
    paging($(this).attr('data-pageNum')*1);
});
// 跳转
function jumpPage() {  
    var num = parseInt($("#jumpWhere").val()); 
    if(num != currentPage_)  
    {  
        paging(num); 
    }  
} 

// 查看诉求信息
function ckeck(appealid,procInstId,Tpl,$place){
    $.ajax({
        url: appBaseURL + "/appeal/queryAppealByAppealId/" + appealid,
        type: 'POST',
        data: JSON.stringify({"userid":userid}),
        contentType: "application/json",
        success: function (info) {
            if(info.code == 0){
                appealData = info.data;
                appealData.category = category;
                // 调用模板引擎
                $place.html(template(Tpl, appealData));
                // 获取当前职能部门的诉求id
                var tasks = info.data.taskList;
                for(var i = 0,len = tasks.length; i < len; i++){
                    if(tasks[i].handleid == userid){
                        task = tasks[i];
                    }
                }
                $('#taskid').val(task.taskid);
            }else{
                toastr.error(info.message,"请求失败，请稍后再试！");
            }
        },
        error: function () {
            toastr.error("请求失败，请稍后再试！");
        } 
    });
    
    //获取流程图
    $.ajax({
        url: appBaseURL + "/processImage/generateImage/" + procInstId,
        type: 'POST',
        contentType: "application/json",
        success: function(info) {
            if (info.code == 0) {
                console.log(info.data);
                $("#img1").attr('src', info.data);
            } else {
                toastr.error("请求失败，请稍后再试！");
            }
        },
        error: function() {
            toastr.error("请求失败，请稍后再试！");
        }
    });
}
appealList.on('click','.getAppeal',function(){;
    var appealid = $(this).parent().attr('data-id');
    var procInstId = $(this).parent().attr('data-procInstId');
    var appealData = {};
    ckeck(appealid,procInstId,'getdisposeTpl',$('#getAppeal'));
});

// 按选中条件查询诉求信息
$('#queryButton').click(function() {
    var tj = {};
        tj.userid = userid;
        tj.taskstatusList = toNumber($('#taskstatusList').val());
        tj.currentusertitle = $('#currentusertitle').val();
        tj.categoryList = toNumber($('#categoryList').val());
        tj.appealtypeList = toNumber($('#appealtypeList').val());
        tj.pageNum = 1;
        tj.pageSize = 20;
    paging(1,tj);
});
$('#currentusertitle').on('keypress',function(event){  
    var theEvent = window.event || event;
    var code = theEvent.keyCode || theEvent.which;
    if(code == 13) {
        var tj = {};
            tj.userid = userid;
            tj.taskstatusList = toNumber($('#taskstatusList').val());
            tj.currentusertitle = $('#currentusertitle').val();
            tj.categoryList = toNumber($('#categoryList').val());
            tj.appealtypeList = toNumber($('#appealtypeList').val());
            tj.pageNum = 1;
            tj.pageSize = 20;
        paging(1,tj);
    }
});

// 刷新
$refresh.click(function () {
    paging(window.pageNow || 1);
    $('#search_form')[0].reset();
    $('#taskstatusList').multiselect('refresh');
    $('#categoryList').multiselect('refresh');
    $('#appealtypeList').multiselect('refresh');
});  

// 处理诉求
$("#table").on('click','#disposeAppeal',function(){
    // 切换页面
    $(".content").animate({
        height:'toggle'
    },500);
    $(".disposeContent").animate({
        height:'toggle'
    },500);
    // 获取诉求信息
    var appealid = $(this).parent().attr('data-id');
    var procInstId = $(this).parent().attr('data-procInstId');
    ckeck(appealid,procInstId,'disposeContentTpl',$('#dispose_Content'));

    // 获取职能部门的id和名称
    setTimeout(function(){
        var functional_id = [];
        var functional_title = [];
        $.ajax({
            url: appBaseURL + '/user/selectUserListByTypeAndCategory',
            type: 'POST',
            data: JSON.stringify({"usertype":1,"category":8}),
            contentType: "application/json",
            success: function (info) {
                if(info.code == 0){
                    var listOption="";
                    for(var i = 0, len = info.data.length; i < len;i++){  
                        listOption +='<option value=' + info.data[i].userid +'>' + info.data[i].title + '</option>'; 
                    }
                    $('#list').html(listOption);
                    setTimeout(function(){
                        $('#list').multiselect({
                            maxHeight: 160,
                            buttonWidth: '150px',
                            buttonText: function(options, select) {
                                if (options.length === 0) {
                                    return '--选择转办部门--';
                                }
                                else if (options.length > 0) {
                                    return '已选查询条件';
                                }
                            }
                        });
                        $('#dispose_Content').find('.btn-group').addClass('dropup');
                    },1);
                }else{
                    toastr.error(info.message);
                }
            },
            error: function () {
                toastr.error("请求失败，请稍后再试！");
            } 
        });
    },100);
});

// 返回
$(".disposeContent").on('click','#back',function(){
    $(".disposeContent").animate({
        height:'toggle'
    },600);
    $(".content").animate({
        height:'toggle'
    },600);
    paging(window.pageNow || 1);
});

// 增加进展信息
$("#dispose_Content").on('click','#addProgress',function(){
    $('.progressContent').slideToggle(500);
});
$("#dispose_Content").on("click",'#submitProgress',function(){
    var formArray = $("#progress").serializeArray();
    var form = arrayToJson(formArray);
    $.ajax({
        type:'POST',
        url: appBaseURL+'/appeal/addTaskProgressinfo/',
        data: form,
        contentType: "application/json",
        success:function(info){
            if(info.code == 0 ){
                toastr.success('提交成功！');
                $('.progressContent').slideToggle(500);
            }else{
                toastr.error("提交失败，请稍后再试！");
            }
        },
        error:function(){
            toastr.error("请求失败，请稍后再试！");
        }
    });
});

// 处理完成
function dispose(data) {
    $.ajax({
        url: appBaseURL + '/appeal/handleTask/',
        type: 'POST',
        data: JSON.stringify(data).replace(/\\\\/g, '/'),
        contentType: "application/json",
        success: function (info) {
            if(info.code == 0){
                toastr.success('处理完毕！');
                // 切换页面
                $(".content").animate({
                    height:'toggle'
                },500);
                $(".disposeContent").animate({
                    height:'toggle'
                },500);
                paging();
            }else{
                toastr.error(info.message);
            }
        },
        error: function () {
            toastr.error("请求失败，请稍后再试！");
        } 
    });
}
// 处理完成，反馈企业
$("#dispose_Content").on('click','#disposed',function(){
    var data = datas($('#disposed'));
    console.log(data);
    dispose(data);
});

// 将诉求退回区镇
$("#dispose_Content").on('click','#backTown',function(){
    var toTaskHandleIds = $(this).attr('data-toTaskHandleIds');
    var toTaskHandleTitels = $(this).attr('data-toTaskHandleTitels');
    var data = datas($('#backTown'));
        data.toTaskHandleIds = toTaskHandleIds;
        data.toTaskHandleTitels = toTaskHandleTitels;
    dispose(data);
});

// 转办至经信委
$("#dispose_Content").on('click','#transmit',function(){
    // 获取经信委的id和名称
    var jxw_id = [];
    var jxw_title = [];
    $.ajax({
        url: appBaseURL + '/user/selectUserListByTypeAndCategory',
        type: 'POST',
        async:false, 
        data: JSON.stringify({"usertype":1,"category":5}),
        contentType: "application/json",
        success: function (info) {
            if(info.code == 0){
                console.log(info.data);
                for(var i = 0, len = info.data.length; i < len; i++){
                    jxw_id[i] = info.data[i].userid*1; 
                    jxw_title[i] = info.data[i].title; 
                }
                $('#transmit').attr('data-toTaskHandleIds',jxw_id);
                $('#transmit').attr('data-taskCurrentProcesslevel',jxw_title);
            }else{
                toastr.error(info.message);
            }
        },
        error: function () {
            toastr.error("请求失败，请稍后再试！");
        } 
    });

    setTimeout(function(){
        var data = datas($('#transmit'));
            data.toTaskHandleIds = $('#transmit').attr('data-toTaskHandleIds')*1;
            data.toTaskHandleTitels = $('#transmit').attr('data-taskCurrentProcesslevel');
        dispose(data);
    },1); 
});

// 转办至市领导
$("#dispose_Content").on('click','#toLeader',function(){
    // 获取经信委的id和名称
    var sld_id = [];
    var sld_title = [];
    $.ajax({
        url: appBaseURL + '/user/selectUserListByTypeAndCategory',
        type: 'POST',
        async:false, 
        data: JSON.stringify({"usertype":1,"category":6}),
        contentType: "application/json",
        success: function (info) {
            if(info.code == 0){
                for(var i = 0, len = info.data.length; i < len; i++){
                    sld_id[i] = info.data[i].userid*1; 
                    sld_title[i] = info.data[i].title; 
                }
                $('#toLeader').attr('data-toTaskHandleIds',sld_id);
                $('#toLeader').attr('data-taskCurrentProcesslevel',sld_title);
            }else{
                toastr.error(info.message);
            }
        },
        error: function () {
            toastr.error("请求失败，请稍后再试！");
        } 
    });

    setTimeout(function(){
        var data = datas($('#toLeader'));
            data.toTaskHandleIds = $('#toLeader').attr('data-toTaskHandleIds')*1;
            data.toTaskHandleTitels = $('#toLeader').attr('data-taskCurrentProcesslevel');
        dispose(data);
    },1); 
});

// 退回至经信委
$("#dispose_Content").on('click','#backJxw',function(){
    // 获取经信委的id和名称
    var jxw_id = [];
    var jxw_title = [];
    $.ajax({
        url: appBaseURL + '/user/selectUserListByTypeAndCategory',
        type: 'POST',
        async:false, 
        data: JSON.stringify({"usertype":1,"category":5}),
        contentType: "application/json",
        success: function (info) {
            if(info.code == 0){
                console.log(info.data);
                for(var i = 0,len = info.data.length; i < len; i++){
                    jxw_id[i] = info.data[i].userid*1; 
                    jxw_title[i] = info.data[i].title; 
                }
                $('#backJxw').attr('data-toTaskHandleIds',jxw_id);
                $('#backJxw').attr('data-taskCurrentProcesslevel',jxw_title);
            }else{
                toastr.error(info.message);
            }
        },
        error: function () {
            toastr.error("请求失败，请稍后再试！");
        } 
    });

    setTimeout(function(){
        var data = datas($('#backJxw'));
            data.toTaskHandleIds = $('#backJxw').attr('data-toTaskHandleIds')*1;
            data.toTaskHandleTitels = $('#backJxw').attr('data-taskCurrentProcesslevel');
            console.log(data);
        dispose(data);
    },50); 
});

// 转职能部门
$("#dispose_Content").on('click','#transmit_functional',function(){
    var toTaskHandleIds = toNumber($('#list').val());
    var toTaskHandleTitels = $('#list option:selected');
    var optionText = [];
    for(var i = 0,len = toTaskHandleTitels.length;i < len; i++){
        optionText[i] = toTaskHandleTitels[i].text;
    }
    var data = datas($('#transmit_functional'));
        data.toTaskHandleIds = toTaskHandleIds;
        data.toTaskHandleTitels = optionText;
    dispose(data);
});

// 附件上传
$('#fileupload').fileupload({
    singleFileUploads : true,
    dataType : 'json',
    done : function(e, data) {
        if (data.result.code == 0) {
            var uploadFiles = data.result.data;
            uploadFiles.forEach(function(filepath) {
                var imageStr = "<div class='upfile'><div class='fileName'><i class='fa fa-paperclip uploadIcon'></i>" 
                                + filepath.upFileName + "(" + (filepath.fileSize/1024).toFixed(2) + "KB)" 
                                + "<a attr='"+ filepath.deletePath 
                                +"'class='delfileButton' onclick='deleteImg(this)' href='#'>&nbsp;[删除]</a></div></div>";
                $("#uploads").append(imageStr);
                imagepaths.push(filepath.serverPath);
            })
        } else {
            alert(data.result.data);
        }
    }
});

// 数据获取
function datas($this) {
    // 图片地址
        var imagepath;
        imagepath = imagepaths.join(",");
    var data = {};
        data.appealId = $this.parent().attr('data-id')*1;
        data.taskId = $('#taskid').val();
        data.toTaskHandleIds = $('#toTaskHandleIds').val()*1;
        data.toTaskHandleTitels = $('#toTaskHandleTitels').val();
        data.taskCurrentProcesslevel = $('#taskCurrentProcesslevel').val()*1;
        data.toTaskprocesslevel = $this.attr('data-id')*1;
        data.replyimage = imagepath;
        data.replycontent = $('#content').val();
    return data;
}